/**
 * Copyright (c) 2010 Jumbomart All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Jumbomart.
 * You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into with
 * Jumbo.
 * 
 * JUMBOMART MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. JUMBOMART SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
 * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
package com.util;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 * I18nUtils
 * 
 * 2013-9-9 下午5:37:37
 * 
 * @author <a href="xinyuan.guo@baozun.cn">郭馨元</a>
 * 
 */
public class I18nUtils {

	private final static Logger log = LoggerFactory.getLogger(I18nUtils.class);

	public static String readI18nString(String source, Locale resolveLocale) {
		String rs = null;
		try {
			JSONObject jo = JSONObject.fromObject(source);
				if (jo != null && resolveLocale != null) {
					String attributeStr = resolveLocale.toString();
					if (jo.has(attributeStr)) {
						rs = (String) jo.get(attributeStr);
					}
				}
		} catch (JSONException ioe) {
			log.debug("trying to resolve a non i18n value {}", source);
		}

		return rs;
	}

	public static String readString(String source, HttpServletRequest req) {
		if (req != null) {
			Locale resolveLocale = RequestContextUtils.getLocale(req);
			return readI18nString(source, resolveLocale);
		}
		return null;
	}
}
